import 'package:aihu_getx_app/app/modules/commons/commons.dart';
import 'package:aihu_getx_app/app/modules/commons/model/dict_data_model.dart';
import 'package:aihu_getx_app/utils/cache_keys.dart';
import 'package:aihu_getx_app/utils/constants.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';

class InitSystemDataUtil {
  InitSystemDataUtil._();

  static String? getDictLabelByTypeAndValue(
      String dictType, dynamic dictValue) {
    if (GetUtils.isNullOrBlank(dictValue)!) {
      return null;
    }
    return getDictListByType(dictType).firstWhereOrNull((element) {
      return element.value == dictValue.toString();
    })?.label;
  }

  static List<DictDataModel> getDictListByType(String dictType) {
    var dictDataMap = SpUtil.getObject(CacheKeys.dictDataMap);
    if (dictDataMap == null) {
      return [];
    }
    var list = dictDataMap[dictType];
    return DictDataModel.fromJsonList(list);
  }

  static void initDictData() {
    var config = Commons.getCurrentClientConfig(clientType: ClientType.c.type);
    var dio = Dio(BaseOptions(
      receiveTimeout: const Duration(seconds: 10),
      connectTimeout: const Duration(seconds: 10),
      sendTimeout: const Duration(seconds: 8),
      responseType: ResponseType.json,
      validateStatus: (_) => true,
      baseUrl: config.serverApiUrl,
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "tenant-id": config.tenantId,
        "app-id": config.appId,
      },
    ));
    dio.get("/system/dict-data/list-all-simple").then((value) async {
      if (value.statusCode == 200) {
        List<Object> list = [];
        Map<String, List<DictDataModel>> dictDataMap = {};
        for (var item in value.data["data"]) {
          var dictDataModel = DictDataModel.fromJson(item);
          list.add(dictDataModel);
          if (dictDataMap.containsKey(dictDataModel.dictType!)) {
            dictDataMap[dictDataModel.dictType!]!.add(dictDataModel);
          } else {
            dictDataMap[dictDataModel.dictType!] = [dictDataModel];
          }
        }
        await SpUtil.remove(CacheKeys.dictDataList);
        await SpUtil.remove(CacheKeys.dictDataMap);
        SpUtil.putObjectList(
          CacheKeys.dictDataList,
          list,
        );
        SpUtil.putObject(
          CacheKeys.dictDataMap,
          dictDataMap,
        );
      }
    });
  }
}
